<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use GatewayWorker\Lib\Gateway;
require_once __DIR__ . '/../../vendor/autoload.php';

// 创建一个Worker监听2345端口，使用http协议通讯
$http_worker = new Worker("http://0.0.0.0:2345");
$http_worker->name = 'http';
// 启动4个进程对外提供服务
$http_worker->count = 1;

//浏览器会多发一个icon的请求:https://www.workerman.net/q/1211
// 接收到浏览器发送的数据时回复hello world给浏览器
$http_worker->onMessage = function(TcpConnection $connection, Request $request)
{
    // 向浏览器发送hello world
    //$connection->send('hello world');
    echo "url:" . $request->path() . " 收到http回调，告诉客户端\n";
    //$json_encode_msg = json_encode(array('ret' => 1, "reason"=>"未处理逻辑"));
    //$msg = "notify_error$json_encode_msg";

    $room_id = $request->header("x-roomid");
    $msgtype = $request->header("x-msg-type");
    $body = $request->rawBody();
    $json_encode_msg = json_encode(array('msg' => $body));

    if($msgtype == "live_comment"){
        $msg = "notify_comment$json_encode_msg";
    }
    elseif($msgtype == "live_gift"){
        $msg = "notify_gift$json_encode_msg";
    }
    elseif($msgtype == "live_like"){
        $msg = "notify_like$json_encode_msg";
    }
    else{
        echo "unahdnle $msgtype \n";
        return;
    }

	echo "room_id:" . $room_id . " msgtype:" . $msgtype . " body:" . $body . "\n";
	//Gateway::sendToClient("7f0000010b5400000001", $msg);
    Gateway::$registerAddress = '127.0.0.1:1238';//config('app.registerIp');
    $client_ids = Gateway::getClientIdByUid($room_id);
    if(count($client_ids) > 0){
        $client_id = $client_ids[0];
        if(Gateway::isOnline($client_id)){
        	echo "send:$client_id msg:" . $msg;
        	Gateway::sendToClient($client_id, $msg);
        }else{
        	echo "offline$client_id";
        }
    }
};

// 如果不是在根目录启动，则运行runAll方法
if(!defined('GLOBAL_START'))
{
	// 运行worker
	Worker::runAll();
}